
package com.v1.video.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.BaseInfo;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.MyloginVcodeOfForgetEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.exception.NetException;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.widgets.MyDialog;

import org.json.JSONException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 修改密码页面
 * @author Administrator
 *
 */
public class PersonPwdModifyActivity extends BaseActivity {

    private final String TAG = "PersonPwdModifyActivity";

    private PersonPwdModifyActivity instance;

    // setText(Html.fromHtml("<u>"+"hahaha"+"</u>"));   

    /** 标题 */
    TextView text_title;

    /** 返回按钮 */
    private ImageView view_btn_return;

    private Button btnSave = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_pwd_modify);
        instance = this;
        initView();
        initData();
        setListener();
    }

    @Override
    protected void initView() {
        // TODO Auto-generated method stub
        view_btn_return = (ImageView) findViewById(R.id.iv_result);
        text_title = (TextView) findViewById(R.id.tv_title);
        
        btnSave = (Button) findViewById(R.id.person_pwd_btn_save);
        
        oldPwEdit = (EditText)findViewById(R.id.person_pwd_cur_input);
        newPwEdit = (EditText)findViewById(R.id.person_pwd_new_input);
        newPeRepeatEdit = (EditText)findViewById(R.id.person_pwd_sure_input);
    }

    @Override
    protected void initData() {
        // TODO Auto-generated method stub
        text_title.setText(R.string.person_pwd_modify);
    }

    @Override
    protected void setListener() {
        // TODO Auto-generated method stub
       
        findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        btnSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            	saveNewPw();
            }
        });
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }

    private EditText oldPwEdit, newPwEdit, newPeRepeatEdit;
    
    private String oldPassword, newPassowrd, newPasswordRepeat;
    
    private void saveNewPw(){
    	
    	oldPassword = oldPwEdit.getText().toString();
    	newPassowrd = newPwEdit.getText().toString();
    	newPasswordRepeat = newPeRepeatEdit.getText().toString();
    	
    	if(oldPassword == null || oldPassword.equals("")){
    		Toast.makeText(instance, "请输入旧密码", Toast.LENGTH_SHORT).show();
    		return;
    	}
		if(newPassowrd == null || newPassowrd.equals("")){
    		Toast.makeText(instance, "请输入新密码", Toast.LENGTH_SHORT).show();
    		return;
		}
		if(newPasswordRepeat == null || newPasswordRepeat.equals("")){
    		Toast.makeText(instance, "请再次输入新密码", Toast.LENGTH_SHORT).show();
    		return;
		}
		if(!newPassowrd.equals(newPasswordRepeat)){
			Toast.makeText(instance, "两次输入新密码不一致", Toast.LENGTH_SHORT).show();
			oldPwEdit.setText("");
	    	newPwEdit.setText("");
	    	newPeRepeatEdit.setText("");
    		return;
		}
    	Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
    	Matcher m = p.matcher(newPassowrd);
    	boolean b = m.matches();
    	if(newPassowrd.length() < 6 ||
    			newPassowrd.length() > 20||
    		!b
    			){
    		Toast.makeText(this, "密码格式错误", Toast.LENGTH_SHORT).show();
    		return;
    	}
		modifyPwd();
		
    }
    
    private ProgressDialog progDialog;
    
    private Thread modifyThread, checkThread;
    private boolean successful;
    private BaseInfo baseInfo;
    
    private final int STATE_MODIFY_PWD_SUCC = 0x0007;
    private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
				case 0:	//修改成功
//					if(checkThread.isAlive()){
//						checkThread.interrupt();
//						checkThread = null;
//					}
//					progDialog.dismiss();
//					progDialog = null;
//					createDialog();
					break;
				case 1:
					Toast.makeText(PersonPwdModifyActivity.this, baseInfo != null?baseInfo.getMsg():"修改失败", Toast.LENGTH_SHORT).show();
//					if(checkThread.isAlive()){
//						checkThread.interrupt();
//						checkThread = null;
//					}
//					progDialog.dismiss();
//					progDialog = null;
					break;
				case 2://连接超时
					Toast.makeText(PersonPwdModifyActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//					if(modifyThread.isAlive()){
//						modifyThread.interrupt();
//						modifyThread = null;
//					}
//					progDialog.dismiss();
//					progDialog = null;
					break;
				case STATE_MODIFY_PWD_SUCC:
					String tokey = (String)msg.obj;
					LoginInfo.getInstance().setToken(tokey);
					LoginInfo.getInstance().saveInstance(getApplicationContext());
					createDialog();
					break;
			}
		}
    	
    };
    
    private void modifyPwd(){
    	
//    	modifyPwdThread();
    	gotoModifyPwd();
//    	checkThread();
    	oldPwEdit.setText("");
    	newPwEdit.setText("");
    	newPeRepeatEdit.setText("");
    	progDialog = Utils.getProgressDialog(PersonPwdModifyActivity.this,"请稍候");
//    	progDialog = ProgressDialog.show(this, null,"请稍候", true, false);
    }
    
    private void gotoModifyPwd(){
    	String key = Constant.getUserCheckKey(LoginInfo.getInstance().getUserId());
		key = MD5.getMessageDigest(key);
		String url = V1VideoHttpApi.GET_MODIFY_OF_PWD_SAFE() + "&devid="
				+ Constant.DEVICEID + "&key=" + key;
		
		Logger.i(TAG, "直接修改密码的Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("uid", LoginInfo.getInstance().getUserId()));
		list.add(new Parameter("password", oldPassword));
		list.add(new Parameter("newpassword", newPassowrd));
		RequestManager.getInstance().postRequest(PersonPwdModifyActivity.this, url, list,
				MyloginVcodeOfForgetEntity.class, 0, "Settingforget2Activity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
						if (object != null) {
							MyloginVcodeOfForgetEntity entity = (MyloginVcodeOfForgetEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								// ToastAlone.showToast(SettingForget1Activity.this,
								// "未知错误", Toast.LENGTH_SHORT);
								return;
							} else if (!header.getStatus().equals("1")) {

								// ToastAlone.showToast(SettingForget1Activity.this,
								// header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {
									if (entity.getBody().getData().getStatus()
											.equals("1")) {
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = STATE_MODIFY_PWD_SUCC;
											msg.obj = entity.getBody().getData().getToken();
											handler.sendMessage(msg);
										}

									} else {
										ToastAlone.showToast(PersonPwdModifyActivity.this, entity
												.getBody().getData()
												.getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
								}
							} else {
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						if(progDialog != null){
							progDialog.dismiss();
						}
						progDialog = null;
					}
				});
    }
    
    private void modifyPwdThread(){
    	
    	successful = false;
    	
    	modifyThread = new Thread(){
    		
    		public void run(){
    			
    			try {
					baseInfo = new NetEngine().updatePwd(LoginInfo.getInstance().getUserId(), oldPassword, newPassowrd);
					successful = true;
					Message msg = new Message();
					if(baseInfo != null && baseInfo.getCode().equals("1")){
						msg.what = 0;
					}
					else{
						msg.what = 1;
					}
					handler.sendMessage(msg);
				} catch (NetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    		}
    		
    	};
    	modifyThread.start();
    	
    	
    }
    
    private void checkThread(){
    	
    	checkThread = new Thread(){
    		
    		public void run(){
    			try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			if(!successful){
					Message msg = new Message();
					msg.what = 2;
					handler.sendMessage(msg);
				}
    			
    		}
    		
    	};
    	checkThread.start();
    	
    }
    
    private void createDialog(){
    	
    	final MyDialog dialog = Utility.createMyDialog(this, R.style.dialog_custom, R.layout.dialog_title_done);
		((TextView)dialog.findViewById(R.id.tv_dialog_title)).setText("密码修改成功");
		((TextView)dialog.findViewById(R.id.tv_dialog_content)).setText("下次登录请使用新密码");
		TextView ok = (TextView)dialog.findViewById(R.id.tv_dialog_ok);
		ok.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		});
		dialog.show();
    	
    }
    
}
